
// 获取全局应用程序实例对象
const app = getApp();

// 组件基础代码
Component({
	behaviors: [],
	properties: {
		upload_progress: {
			type: String,
			value: 0
		},
		serverType: {
            type: String,
            value: ''
        },
        url: {
        	type: String,
        	value: 'https://api2.wii.qq.com/utils/fileupload/image'
        },
        size: {
        	type: Number,
        	value: 2
        },
		width: {
			type: String,
			value: '140rpx'
		},
		height: {
			type: String,
			value: '140rpx'
		},
		files: {
			type: Array,
			value: []
		},
		count: {
            type: Number,
            value: 1,
            observer: function(newVal, oldVal) {
                if (newVal > 9) {
                    return newVal = 9;
                } else if (newVal < 1) {
                    return newVal = 1;
                }
            }
        }
	},
	data: {
        currentIndex: 0
	},
	ready(){
        var files = [
            '../../images/logo.png',
            '../../images/main.png'
        ];
		this.setData({
			files: files,
            currentIndex: files.length
		})
	},
	methods: {
		chooseImage() {
			const that = this;
            var {count,files,currentIndex} = this.data;
			wx.chooseImage({
				count: that.data.count, // 默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					var tempFilePaths = res.tempFilePaths;
                    var limit = files.length;
                    console.log(`limit->${limit}`);
                    console.log(count,files.length,tempFilePaths.length);
                    if(files.length+tempFilePaths.length>count){
                        wx.showToast({
                            title: `不能超过${count}张图片！`,
                            duration: 2000
                        });
                        return false;
                    }
					for (let i = 0; i < tempFilePaths.length; i++) {
                        var tempFilePath = tempFilePaths[i];
                        that.data.files.push(tempFilePath);
                        that.setData({
                            files: that.data.files
                        });
                        var fileName;
                        try{
                          fileName = tempFilePath.match(/(http:\/\/tmp\/)(.+)/)[2];
                        }catch(e){
                          fileName = tempFilePath.match(/(wxfile:\/\/)(.+)/)[2];
                        }
                        if (that.data.serverType == 'qcloud') {
                            app.utils.cos(tempFilePath, fileName, (res) => {
                                currentIndex++;
                                var result = {
                                  ret: res.code,
                                  msg: res.message,
                                  data:{
                                    image_url: res.data.access_url
                                  }
                                }
                                files.splice(limit + i, 1, res.data.image_url);
                                that.setData({
                                  files: that.data.files,
                                  currentIndex: currentIndex
                                });
                                that._emitEvents(result);
                            },(res)=>{
                                that.setData({
                                    upload_progress: res.progress
                                })
                                if (res.progress === 100) {
                                    that.setData({
                                        upload_progress: 0
                                    })
                                }
                            });
                        } else {
                            wx.uploadFile({
                                url: that.data.url,
                                filePath: tempFilePath,
                                name: 'file',
                                header: {
                                    WXAPP: 'qq.com'
                                },
                                success: function(res) {
                                    var res = JSON.parse(res.data);
                                    currentIndex++;
                                    if(res.ret==0){
                                        var size = res.data.size[that.data.size];
                                        var imgUrl =  res.data.image_url.replace(/\/[0-9]+(?=[^0-9]*$)/, '/' + size);
                                        files.splice(limit + i, 1, imgUrl);
                                    }else{
                                        files.pop();
                                    }
                                    that.setData({
                                      files: files,
                                      currentIndex:currentIndex
                                    });
                                    that._emitEvents(res);
                                },
                                fail: function(res) {
                                    var msg = res.msg||res.errMsg;
                                    wx.showToast({
                                        title: msg,
                                        image: '/images/warning.svg',
                                        duration: 2000
                                    });
                                    files.pop();
                                    that.setData({
                                      files: files
                                    });
                                }
                            })
                        }
                    }
				}
			})
		},
		deleteImage(evt){
			const that = this;
			let {index} = evt.currentTarget.dataset;
            console.log(index);
			that.data.files.splice(index,1);
			that.setData({
				files: that.data.files,
                currentIndex: that.data.currentIndex - 1
			})
		},
		_emitEvents: function(res) {
			var that = this;
			that.triggerEvent('wiiUploadEvent', res);
		}
	}
});
